package Day2025_03_10;

import java.util.LinkedList;
import java.util.Queue;

public class LeetCode1020 {
    int[] dx = {0, 0, -1, 1};
    int[] dy = {-1, 1, 0, 0};
    public int numEnclaves(int[][] grid) {
        int m  =grid.length, n = grid[0].length;
        boolean[][] vis = new boolean[m][n];
        Queue<int[]> q =  new LinkedList<>();
        for (int i = 0; i < m; i++) {
            if (grid[i][0] == 1) {
                q.add(new int[]{i, 0});
                vis[i][0] = true;
            }
            if (grid[i][n - 1] == 1) {
                q.add(new int[]{i, n - 1});
                vis[i][n - 1] = true;
            }
        }
        for (int j = 0; j < n; j++) {
            if (grid[0][j] == 1) {
                q.add(new int[]{0, j});
                vis[0][j] = true;
            }
            if (grid[m - 1][j] == 1) {
                q.add(new int[]{m - 1, j});
                vis[m - 1][j] = true;
            }
        }
        while (!q.isEmpty()) {
            int sz = q.size();
            while (sz-- != 0) {
                int[] tmp = q.poll();
                int a = tmp[0], b = tmp[1];
                for (int i = 0 ; i < 4; i++) {
                    int x = a + dx[i], y = b + dy[i];
                    if (x >= 0 && x <m && y >= 0 && y < n && !vis[x][y] && grid[x][y] == 1) {
                        q.add(new int[] {x, y});
                        vis[x][y] = true;
                    }
                }
            }
        }
        int ret = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (!vis[i][j] && grid[i][j] == 1) ret++;
            }
        }
        return ret;
    }
}
